package com.neu.cloudfactory.controler;

import com.neu.cloudfactory.bean.Order.*;
import com.neu.cloudfactory.bean.Product.Product;
import com.neu.cloudfactory.repository.*;
import com.neu.cloudfactory.util.DateFormat;
import com.neu.cloudfactory.util.OrderNumber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.Tuple;
import java.util.*;

@RestController
public class OrderControler {
    @Autowired
    OrderRepository orderRepository;
    @Autowired
    OrderstatusRepository orderstatusRepository;
    @Autowired
    ProductRepository productRepository;
    @Autowired
    RecevierRepository recevierRepository;
    @Autowired
    SchedulingRepository schedulingRepository;


    @RequestMapping("/order/findAll/{page}/{size}")
    public Page<Ordering> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        Pageable pageable = PageRequest.of(page-1,size);
        return orderRepository.findAll(pageable);
    }

    @RequestMapping("/order/findAllByUserid/{page}/{size}/{userid}")
    public Page<Ordering> findAllByUserid(@PathVariable("page") Integer page, @PathVariable("size") Integer size, @PathVariable("userid") Integer userid) {
        Pageable pageable = PageRequest.of(page-1,size);
        return orderRepository.findAllByUserid(userid,pageable);
    }
    @RequestMapping("/order/manageriorderlist/{page}/{size}")
    public Page<Ordering> manageriorderlist(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        Pageable pageable = PageRequest.of(page-1,size);
        return orderRepository.findAllByStatusidBetween(2,5,pageable);
    }


    @RequestMapping("/order/getProductname")
    public List<ProductIdAndName> getProductname(){
        List<Product> products = productRepository.findAll();
        List<ProductIdAndName> productNames = new ArrayList<>();

        for (Product product : products) {
            productNames.add(new ProductIdAndName(product.getId(),product.getName()));
        }
        return productNames;
    }

    @RequestMapping("/order/getReceviers")
    public List<Recevier> getReceviers(){
        return recevierRepository.findAll();
    }

    @RequestMapping("/order/changestatus/{id}/{statusid}")
    public String changeStatus(@PathVariable("id") Integer id,@PathVariable("statusid") Integer statusid){
        Ordering order = orderRepository.getById(id);
        boolean complete = false;
        if(statusid == order.getStatusid()){
            switch (statusid){
                case 1:
                    order.setStatusid(2);
                    break;
                case 2:
                    order.setStatusid(1);
                    break;
                case 6:
                    order.setStatusid(7);
                    break;
            }
            orderRepository.save(order);
            complete = true;
        }
        return complete?"success":"failed";
    }

    @RequestMapping("/order/managechangestatus/{id}/{statusid}")
    public String managechangestatus(@PathVariable("id") Integer id,@PathVariable("statusid") Integer statusid){
        Ordering order = orderRepository.getById(id);
        boolean complete = false;
        if(statusid == order.getStatusid() && order.getStatusid()==5 && !schedulingRepository.existsByOrderid(id)){
            order.setStatusid(6);
            orderRepository.save(order);
            complete = true;
        }
        return complete?"success":"failed";
    }
    @RequestMapping("/orderstatus/findAll")
    public List<Orderstatus> statusfindAll() {
        return orderstatusRepository.findAll();
    }

    @RequestMapping("/order/deleteById/{id}")
    public String delete(@PathVariable("id") Integer id){
        try{
            orderRepository.deleteById(id);
            return "success";
        }catch (Exception e){
            return "failed";
        }
    }

    @RequestMapping("/order/add")
    public String add(@RequestBody HashMap<String,String> params){
        Ordering ordering = new Ordering();
        try{
            String receiver = params.get("receiver");
            String address = params.get("address");
            String connection = params.get("connection");
            int userid = Integer.parseInt(params.get("userid"));

            Optional<Recevier> tmp = recevierRepository.findByNameAndAddressAndConnection(receiver,address,connection);
            Recevier rec;
            if(tmp.isPresent()){
                rec = tmp.get();
            }else {
                rec = recevierRepository.save(new Recevier(null,receiver,address,connection));
            }

            String number = OrderNumber.getOrderNumber();
            while (orderRepository.existsByNumber(number)){
                number = OrderNumber.getOrderNumber();
            }

            ordering.setNumber(number);
            ordering.setProductid(Integer.parseInt(params.get("productid")));
            ordering.setNum(Integer.parseInt(params.get("num")));
            ordering.setDeliverydate(DateFormat.StringToDate(params.get("deliverydate")));
            ordering.setTenderdate(DateFormat.StringToDate(params.get("tenderdate")));
            ordering.setRecevierid(rec.getId());
            ordering.setStatusid(1);
            ordering.setUserid(userid);
            ordering.setTenderid(0);

            orderRepository.save(ordering);
            return "success";
        }catch (Exception e){
            return "failed";
        }
    }
    @RequestMapping("/order/update")
    public String update(@RequestBody HashMap<String,String> params){
        Ordering ordering = new Ordering();
        try{
            if(params.get("id")!=null){
                ordering.setId(Integer.parseInt(params.get("id")));
            }
            String receiver = params.get("receiver");
            String address = params.get("address");
            String connection = params.get("connection");
            int userid = Integer.parseInt(params.get("userid"));

            Optional<Recevier> tmp = recevierRepository.findByNameAndAddressAndConnection(receiver,address,connection);
            Recevier rec;
            if(tmp.isPresent()){
                rec = tmp.get();
            }else {
                rec = recevierRepository.save(new Recevier(null,receiver,address,connection));
            }

            String number = OrderNumber.getOrderNumber();
            while (orderRepository.existsByNumber(number)){
                number = OrderNumber.getOrderNumber();
            }

            ordering.setNumber(number);
            ordering.setProductid(Integer.parseInt(params.get("productid")));
            ordering.setNum(Integer.parseInt(params.get("num")));
            ordering.setDeliverydate(DateFormat.StringToDate(params.get("deliverydate")));
            ordering.setTenderdate(DateFormat.StringToDate(params.get("tenderdate")));
            ordering.setRecevierid(rec.getId());
            ordering.setStatusid(1);
            ordering.setUserid(userid);
            ordering.setTenderid(0);

            orderRepository.save(ordering);
            return "success";
        }catch (Exception e){
            return "failed";
        }
    }

    @RequestMapping("/order/findById/{id}")
    public Ordering findById(@PathVariable("id") Integer id){
        return orderRepository.findById(id).get();
    }
    @RequestMapping("/order/getOrderById/{id}")
    public OrderResult getOrderById(@PathVariable("id") Integer id){
        Ordering order=orderRepository.getById(id);
        Recevier recevier=recevierRepository.getById(order.getRecevierid());
        OrderResult orderResult = new OrderResult();

        orderResult.setId(order.getId());
        orderResult.setProductid(order.getProductid());
        orderResult.setUserid(order.getUserid());
        orderResult.setDeliverydate(order.getDeliverydate());
        orderResult.setTenderdate(order.getTenderdate());
        orderResult.setNum(order.getNum());
        orderResult.setConnection(recevier.getConnection());
        orderResult.setAddress(recevier.getAddress());
        orderResult.setReceiver(recevier.getName());

        return orderResult;
    }



}
